import logging
import json
import math
import os

from util.read_excel_file import ReadExcel   # 从 util 包里导入 ReadExcel 类

logger = logging.getLogger(__name__)
class DipCatalog:

    #读取核心目录(column_name:列明，value=具体值)
    def load_core_catalog(self, column_name, value):

        try:
            reader = ReadExcel('DIP病种目录库_核心综合目录 V2.0.xlsx')
            catalog_data = reader.load_catalog_data()

            if catalog_data.empty:
                return json.dumps({
                    "status": "warning",
                    "message": "dip核心目录文件为空或者格式错误",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"DIP病种目录库_核心综合目录，共 {len(catalog_data)} 条记录")

            matches = catalog_data[catalog_data[column_name] == value]

            if matches.empty:
                logger.info(f"未找到 {column_name}={value} 的记录")
                return json.dumps({
                    "status": "not_found",
                    "message": f"未找到 {column_name}={value} 的记录",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"查询到 {len(matches)} 条 {column_name}={value} 的记录")
            data_list = matches.to_dict(orient="records")

            # NaN 转 None
            for record in data_list:
                for k, v in record.items():
                    if isinstance(v, float) and math.isnan(v):
                        record[k] = None

            return json.dumps({
                "status": "success",
                "message": f"查询到 {len(matches)} 条 {column_name}={value} 的记录",
                "data": data_list
            }, ensure_ascii=False)

        except Exception as e:
            logger.error(f"加载DIP病种目录库_核心综合目录时发生错误: {str(e)}")
            return json.dumps({
                "status": "error",
                "message": f"加载DIP病种目录库_核心综合目录时发生错误: {str(e)}",
                "data": []
            }, ensure_ascii=False)

    # 读取年龄辅助目录(column_name:列明，value=具体值)
    def load_age_supplementary_catalog(self, column_name, value):

        try:
            reader = ReadExcel('年龄辅助目录.xlsx')
            age_catalog_data = reader.load_catalog_data()

            if age_catalog_data.empty:
                return json.dumps({
                    "status": "warning",
                    "message": "dip年龄辅助目录文件为空或者格式错误",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"DIP年龄辅助目录，共 {len(age_catalog_data)} 条记录")

            matches = age_catalog_data[age_catalog_data[column_name] == value]

            if matches.empty:
                logger.info(f"未找到 {column_name}={value} 的记录")
                return json.dumps({
                    "status": "not_found",
                    "message": f"未找到 {column_name}={value} 的记录",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"查询到 {len(matches)} 条 {column_name}={value} 的记录")
            data_list = matches.to_dict(orient="records")

            # NaN 转 None
            for record in data_list:
                for k, v in record.items():
                    if isinstance(v, float) and math.isnan(v):
                        record[k] = None

            return json.dumps({
                "status": "success",
                "message": f"查询到 {len(matches)} 条 {column_name}={value} 的记录",
                "data": data_list
            }, ensure_ascii=False)

        except Exception as e:
            logger.error(f"加载年龄辅助目录时发生错误: {str(e)}")
            return json.dumps({
                "status": "error",
                "message": f"加载年龄辅助目录时发生错误: {str(e)}",
                "data": []
            }, ensure_ascii=False)

    # 读取床日辅助目录(column_name:列明，value=具体值)
    def load_bed_supplementary_catalog(self, column_name, value):

        try:
            reader = ReadExcel('床日病种目录库.xlsx')
            bed_catalog_data = reader.load_catalog_data()

            if bed_catalog_data.empty:
                return json.dumps({
                    "status": "warning",
                    "message": "dip床日辅助目录文件为空或者格式错误",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"DIP床日辅助目录，共 {len(bed_catalog_data)} 条记录")

            matches = bed_catalog_data[bed_catalog_data[column_name] == value]

            if matches.empty:
                logger.info(f"未找到 {column_name}={value} 的记录")
                return json.dumps({
                    "status": "not_found",
                    "message": f"未找到 {column_name}={value} 的记录",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"查询到 {len(matches)} 条 {column_name}={value} 的记录")
            data_list = matches.to_dict(orient="records")

            # NaN 转 None
            for record in data_list:
                for k, v in record.items():
                    if isinstance(v, float) and math.isnan(v):
                        record[k] = None

            return json.dumps({
                "status": "success",
                "message": f"查询到 {len(matches)} 条 {column_name}={value} 的记录",
                "data": data_list
            }, ensure_ascii=False)

        except Exception as e:
            logger.error(f"加载床日辅助目录时发生错误: {str(e)}")
            return json.dumps({
                "status": "error",
                "message": f"加载床日辅助目录时发生错误: {str(e)}",
                "data": []
            }, ensure_ascii=False)

    # 读取excel公共函数(column_name:列明，value=具体值)
    def load_base_catalog_excel(self, file_name,column_name, value):
        try:
            new_file_name = os.path.splitext(file_name)[0]
            reader = ReadExcel(file_name)
            base_catalog_data = reader.load_catalog_data()

            if base_catalog_data.empty:
                return json.dumps({
                    "status": "warning",
                    "message": new_file_name+"文件为空或者格式错误",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"{new_file_name}，共 {len(base_catalog_data)} 条记录")

            matches = base_catalog_data[base_catalog_data[column_name] == value]

            if matches.empty:
                logger.info(f"未找到 {column_name}={value} 的记录")
                return json.dumps({
                    "status": "not_found",
                    "message": f"未找到 {column_name}={value} 的记录",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"查询到 {len(matches)} 条 {column_name}={value} 的记录")
            data_list = matches.to_dict(orient="records")

            # NaN 转 None
            for record in data_list:
                for k, v in record.items():
                    if isinstance(v, float) and math.isnan(v):
                        record[k] = None

            return json.dumps({
                "status": "success",
                "message": f"查询到 {len(matches)} 条 {column_name}={value} 的记录",
                "data": data_list
            }, ensure_ascii=False)

        except Exception as e:
            logger.error(f"加载{new_file_name}时发生错误: {str(e)}")
            return json.dumps({
                "status": "error",
                "message": f"加载{new_file_name}时发生错误: {str(e)}",
                "data": []
            }, ensure_ascii=False)

    def load_surgery(self, column_name, value):

        try:
            reader = ReadExcel('手术表.xlsx')
            catalog_data = reader.load_catalog_data()

            if catalog_data.empty:
                return json.dumps({
                    "status": "warning",
                    "message": "手术表文件为空或者格式错误",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"手术表目录，共 {len(catalog_data)} 条记录")

            matches = catalog_data[catalog_data[column_name] == value]

            if matches.empty:
                logger.info(f"未找到 {column_name}={value} 的记录")
                return json.dumps({
                    "status": "not_found",
                    "message": f"未找到 {column_name}={value} 的记录",
                    "data": []
                }, ensure_ascii=False)

            logger.info(f"查询到 {len(matches)} 条 {column_name}={value} 的记录")
            data_list = matches.to_dict(orient="records")

            # NaN 转 None
            for record in data_list:
                for k, v in record.items():
                    if isinstance(v, float) and math.isnan(v):
                        record[k] = None

            return json.dumps({
                "status": "success",
                "message": f"查询到 {len(matches)} 条 {column_name}={value} 的记录",
                "data": data_list
            }, ensure_ascii=False)

        except Exception as e:
            logger.error(f"加载手术表时发生错误: {str(e)}")
            return json.dumps({
                "status": "error",
                "message": f"加载手术表时发生错误: {str(e)}",
                "data": []
            }, ensure_ascii=False)